'use strict';

const { Service } = require('egg');

class SpecialService extends Service {
  async insert({ name }) {
    const now = Date.now();
    const id = `special-${now}`;
    const { affectedRows } = await this.app.db.mybatisQuery({
      namespace: 'special',
      sqlId: 'insert',
      params: { id, name },
    });
    if (affectedRows === 1) {
      return await this.selectById({ id });
    }
    return null;
  }

  async selectById({ id }) {
    const rows = await this.app.db.mybatisQuery({
      namespace: 'special',
      sqlId: 'selectById',
      params: { id },
    });
    if (rows.length === 1) return rows[0];
    return null;
  }

  async selectByPage({ page, size }) {
    return await this.app.db.mybatisQuery({
      namespace: 'special',
      sqlId: 'selectByPage',
      params: { limit: size, offset: (page - 1) * size },
    });
  }

  async updateById({ id, name }) {
    const { affectedRows } = await this.app.db.mybatisQuery({
      namespace: 'special',
      sqlId: 'updateById',
      params: { id, name },
    });
    return affectedRows === 1;
  }

  async deleteById({ id }) {
    const { affectedRows } = await this.app.db.mybatisQuery({
      namespace: 'special',
      sqlId: 'deleteById',
      params: { id },
    });
    return affectedRows === 1;
  }
}

module.exports = SpecialService;
